<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>
    <button onclick="doAjaxGet()">do Ajax get</button>
    <button onclick="doAjaxPost()">do Ajax Post</button>
    <button onclick="doAjaxDelete()">Do Ajax Delete</button>
    <button onclick="doAjaxPut()">Do Ajax Put</button>
</div>

<div id="result"></div>

<script>
    function doAjaxGet() {
        let xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                document.getElementById("result").innerHTML = xhr.responseText;
            }
        }
        xhr.open("get", "http://localhost:8080/doAjaxGet", true);
        xhr.send(null);
    }

    function doAjaxPost() {
        let xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                document.getElementById("result").innerHTML = xhr.responseText;
            }
        }
        xhr.open("post", "http://localhost:8080/doAjaxPost", true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.send("id=200&name=xiaomi&remark=very good");
    }

    function doAjaxDelete() {
        let xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    document.getElementById("result").innerHTML = xhr.responseText;
                }
            }
        }
        //当做一个添加操作，或者向服务端提交的数据比较多时可以考虑使用post请求
        xhr.open("delete", "http://localhost:8080/doAjaxDelete/200", true);
        xhr.send(null);
    }

    //通过Put请求实现更新操作
    function doAjaxPut() {
        let xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    document.getElementById("result").innerHTML = xhr.responseText;
                }
            }
        }
        //当做一个更新操作，可以考虑使用put请求
        xhr.open("PUT", "http://localhost:8080/doAjaxPut", true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.send("id=200&name=oppo&remark=nice");//put请求数据要写到send方法内部
    }
</script>
</body>
</html>